/**
 *	流程模块主Flow录入页使
 *	开发者：雨中磐石
 *	地址：www.rockoa.com
 *	日期：2023-07-19
 */

package com.framework.Flow;


import com.framerock.db.DB;
import com.framerock.baselib.CDate;
import com.framerock.baselib.Json;
import com.framerock.baselib.Patter;
import com.framerock.baselib.Rock;

import java.util.ArrayList;
import java.util.Map;

public class FlowInput extends FlowBase {

    public FlowInput(Flow flows) {
        super(flows);
    }


    /**
     * 录入保存
     * */
    public String saveData(String mid)
    {
        if(mFlow.isError())return "";
        ArrayList<Map<String, String>> farr = mFlow.getFieldsArr(0);
        if(farr == null)return mFlow.setError("没有字段");
        Json json = new Json();
        Map<String, String> da,rs,savedata = Rock.getMap(),before,savemap,fobj = null,olddata = mFlow.data;
        String val,fid,nam,type,attr,onlywhere="",str,arr1[];
        if(mFlow.isCompanymode())onlywhere = "and `cid`="+mRequest.COMPANYID+"";

        int i,to;
        String owhere = Rock.getMapString(mFlow.moders, "where");
        ArrayList<Map<String, String>> subdata = Rock.getMapList();
        for(i=0;i<farr.size();i++){
            da  = farr.get(i);
            if(!da.get("islu").equals("1"))continue;

            fid = da.get("fields");
            type = da.get("fieldstype");
            nam = da.get("name");
            attr= da.get("attr");

            val = mRequest.post(fid);
            if(da.get("isbt").equals("1")){
                if(Rock.isEmpt(val))return mFlow.setError(""+nam+"不能为空");
            }
            if(!Rock.isEmpt(val)) {
                str  = this.checkValue(val, attr, fid);
                if(!Rock.isEmpt(str))return mFlow.setError(""+nam+""+str+"");

                //唯一值判断
                if (da.get("isonly").equals("1")){
                    String where = "`id`<>" + mid + " "+onlywhere+" and `" + fid + "`='" + val + "'";
                    if (!Rock.isEmpt(owhere)) where += " and " + owhere + "";
                    to = mFlow.mModel.getCount(where);
                    if (to > 0) return mFlow.setError("" + nam + "(" + val + ")已存在");
                }
            }
            savedata.put(fid, val);

            if(type.indexOf("change")==0) {
                str = da.get("data");
                if(!Rock.isEmpt(str)){
                    arr1 = str.split(",");
                    fid  = arr1[0];
                    val  = mRequest.post(fid);
                    savedata.put(fid, val);
                }
            }

            if(type.indexOf("selectdata")==0) {
                str = da.get("data");
                if(!Rock.isEmpt(str)){
                    arr1 = str.split(",");
                    if(arr1.length>1){
                        fid = arr1[1];
                        val = mRequest.post(fid);
                        savedata.put(fid, val);
                    }
                }
            }

            //子表
            if(type.equals("subdata")) {
                rs  = mFlow.subdataInfo(da.get("data"));
                if(rs != null){
                    str = rs.get("num");
                    val = mRequest.post(fid+"_value");
                    fid = rs.get("fid");
                    if(!Rock.isEmpt(val))subdata.add(Rock.getMap("num="+str+",fid="+fid+",val="+val+""));
                }
            }
        }

        Boolean isadd = false;
        if(mid.equals("0"))isadd = true;

        before = mFlow.mFlowListener.onSavebefore(savedata, mid, isadd);
        if(mFlow.isError())return "";

        if(before != null){
            String savefields   = Rock.getMapString(before, "savefields");//要保存字段如："abc=val,abc1=val1"
            String notsave      = Rock.getMapString(before, "notsave");//不保存字段如："abc,abc1"
            String msg          = Rock.getMapString(before, "msg");//错误的提示
            if(!Rock.isEmpt(msg))return mFlow.setError(msg);
            if(!Rock.isEmpt(notsave)) {
                arr1 = notsave.split(",");
                for(i=0;i<arr1.length;i++)savedata.remove(arr1[i]);
            }
            if(!Rock.isEmpt(savefields)) {
                savemap = Rock.getMap(savefields);
                savedata= Rock.joinMap(savedata, savemap);
            }
        }

        if(mFlow.UnitModeBo && mFlow.isflow > 0){
            savedata.put("status", "0");
        }

        //返回主表所有字段，判断字段是否存在从主表读取
        ArrayList<Map<String, String>> fidarr = this.nDb.getColumns(DB.chuliPerfix(mFlow.table));
        if(fidarr != null){
        	fobj = Rock.getMap();
            for(i=0;i<fidarr.size();i++){
                da = fidarr.get(i);
                fobj.put(da.get("fields"), da.get("type"));
            }
            for (Map.Entry<String, String> entry : savedata.entrySet()) {
                fid    = entry.getKey();
                val    = entry.getValue();
                type   = Rock.getMapString(fobj, fid);
                if(Rock.isEmpt(type))return mFlow.setError("主表("+mFlow.table+")的字段("+fid+")不存在");
                type   = this.getdbtype(type);
                if(Rock.isEmpt(val)){
                    if(type.equals("date"))savedata.put(fid, null);
                    if(type.equals("int"))savedata.put(fid, "0");
                }else{
                    if(type.equals("int")){
                        if(!Patter.isnumber(val))return mFlow.setError("字段("+fid+")必须是数字");
                    }
                }
            }
        }

        String optname = mRequest.getLoginrs("name");
        if(mRequest.USERABOOL)optname = mRequest.getUserars("name");
        
        val  = savedata.get("optdt");
        if(val==null) {
        	type = Rock.getMapString(fobj, "optdt");
        	if(Rock.contain(type, "date"))savedata.put("optdt", CDate.now());
        }

        val  = savedata.get("optname");
        if(val==null) {
            type = Rock.getMapString(fobj, "optname");
            if(!Rock.isEmpt(type))savedata.put("optname", optname);
        }

        if(isadd) {

            type = Rock.getMapString(fobj, "cid");
            if(Rock.contain(type, "int"))savedata.put("cid", mRequest.COMPANYID);

        	val  = savedata.get("adddt");
        	if(val==null) {
        		type = Rock.getMapString(fobj, "adddt");
        		if(Rock.contain(type, "date"))savedata.put("adddt", CDate.now());
        	}

            val  = savedata.get("uid");
            if(val==null) {
                type = Rock.getMapString(fobj, "uid");
                if(Rock.contain(type, "int"))savedata.put("uid", mRequest.USERID);
            }

            val  = savedata.get("aid");
            if(val==null) {
                type = Rock.getMapString(fobj, "aid");
                if(Rock.contain(type, "int"))savedata.put("aid", mRequest.USEAID);
            }

            int nid = mFlow.mModel.insert(savedata);
            if(nid==0)return mFlow.setError(this.nDb.error());
            mid     = ""+nid+"";
        }else{
            Boolean sbo = mFlow.mModel.update(savedata, mid);
            if(!sbo)return mFlow.setError(this.nDb.error());
        }

        //子表保存的
        for(i=0;i<subdata.size();i++){
            da = subdata.get(i);
            Flow flow = Flow.get(this.nDb, da.get("num"), mRequest);
            fid= da.get("fid"); val= da.get("val");
            flow.mModel.update("`"+fid+"`="+mid+"", "`"+fid+"`="+val+"");
        }


        mFlow.mFlowListener.onSaveafter(savedata, mid, isadd);

        //保存修改记录里
        if(!isadd){

        }


        //保存到操作记录flowlog表里
        if(mFlow.isCompanymode() && mRequest.COMPANYBOOL) {
            mFlow.initData(mid);
            int isturn = Integer.parseInt(mRequest.post("sysisturn", "0"));
            if(mFlow.isflow > 0)isturn = 1;
            this.submit(isturn);
            if(isadd){
                mFlow.sendTodo(FlowTodo.ACTTYPE_TURN);
            }else{
                mFlow.sendTodo(FlowTodo.ACTTYPE_EDIT);
            }
        }

        //初始流程并提交到审批
        json.putVal("mid", mid);

        return  json.getJson();
    }

    /**
     * 提交到流程里
     * */
    public void submit(int isturn)
    {
        String name = "保存";
        if(isturn==1)name = "提交";
        mFlow.addLog(name, "", null);
        if(mFlow.isflow > 0 && mFlow.UnitModeBo)mFlow.submitFlow();
    }

    //字段验证
    public String checkValue(String val, String attr, String fid)
    {
        if(fid.equals("num"))attr+=" onlyen len2";
        if(fid.equals("table"))attr+=" onlyen noint len2";
        if(Rock.contain(attr, "onlyen")){
            if(!Patter.iszgen(val))return "必须英文数字组合不能特殊符号";
        }
        if(Rock.contain(attr, "mobile")){
            if(val.length()<6)return "必须6位以上";
            if(val.length()>11)return "不能超过11位数";
            if(!Patter.isnumber(val))return "必须是数字组合";
        }
        if(Rock.contain(attr, "noint")){
            if(Patter.isnumber(val))return "不能是数字";
        }
        if(Rock.contain(attr, "len2")){
            if(val.length()<2)return "必须2位以上";
        }
        return "";
    }

    /**
     * 获取字段的默认值
     * */
    public ArrayList<Map<String, String>> devFieldsarr(ArrayList<Map<String, String>> rows)
    {
        Map<String, String> da;
        String dev;
        FlowWhere owhere = mFlow.mFlowBase.Where();
        if(rows != null)for(int i=0;i<rows.size();i++){
            da = rows.get(i);
            dev= da.get("dev");
            if(!Rock.isEmpt(dev) && dev.indexOf("{")>-1){
                dev = owhere.defaultValue(dev);
                rows.get(i).put("dev", dev);
            }
        }
        return rows;
    }


    //编辑时获取文件信息
    public String getAllFileids()
    {
        ArrayList<Map<String, String>> farr    = mFlow.getFieldsArr(0);
        Map<String, String> da;
        String fid,type,val,fileids="";
        for(int i=0; i<farr.size();i++){
            da   = farr.get(i);
            fid  = da.get("fields");
            type = da.get("fieldstype");
            if(type.equals("uploadfile")){
                val = Rock.getMapString(mFlow.data, fid);
                if(!Rock.isEmpt(val)){
                    if(!Rock.isEmpt(fileids))fileids+=",";
                    fileids+=val;
                }
            }
        }
        return fileids;
    }

    //返回字段类型
    private String getdbtype(String type)
    {
        if(Rock.isEmpt(type))return type;
        if(Rock.contain(type, "date")){
            type = "date";
        }else if(
           Rock.contain(type,"int(")
               || Rock.contain(type,"decimal")
               || Rock.contain(type,"integer")
        ){
            type = "int";
        }
        return type;
    }
}
